package uit.ce03.game_ninja.MainGame;

import java.io.IOException;
import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.BoundCamera;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.TextMenuItem;
import org.anddev.andengine.entity.scene.menu.item.decorator.ColorMenuItemDecorator;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;

import uit.ce03.game_ninja.NinjaActivity;
import uit.ce03.game_ninja.R;
import uit.ce03.game_ninja.Static.Static_Const;
import uit.ce03.game_ninja.database.Database;
import uit.ce03.game_ninja.map.Map;
import uit.ce03.game_ninja.map.MyMap;
import uit.ce03.game_ninja.mutitouch.MultiTouch;
import uit.ce03.game_ninja.mutitouch.MultiTouchController;
import uit.ce03.game_ninja.player.Player;
import uit.ce03.game_ninja.player.Status_player;
import uit.ce03.game_ninja.quaivat.quaivat;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;

public class MainGame_BaseGame extends BaseGameActivity implements IOnSceneTouchListener,IOnMenuItemClickListener {
	private Player mPlayer;
	private Scene mScene;
	private BoundCamera mCamera;
	private Scene mScene_loading;
	private quaivat mQuaivat;
	// map
	private TMXTile mTMXtile;
	private TMXTiledMap mTMXTiledMap;
	private TMXLayer mTMXVatCan_Layer;
	private TMXLayer mTMXVatcan_QuaiVat;
	private MyMap mMap;
	
	
	private DigitalOnScreenControl mDigitalOnScreenControl;
	private int mStatus_DigitalOnScreenControl;
	private BitmapTextureAtlas mOnControlScreenTexture;
	private TextureRegion mOnScreenControlBaseTextureRegion;
    private TextureRegion mOnScreenControlKnobTextureRegion;
    // icon jump on screen
    private BitmapTextureAtlas mJumpTexture;
    private TextureRegion mJumpTextureRegion;
    private Sprite mJumpSprite;
    // icon Fight on screen
    private BitmapTextureAtlas mFightTexture;
    private TextureRegion mFightTextureRegion;
    private Sprite mFightSprite;
    // icon heart
    private BitmapTextureAtlas mHeartTexture;
    private TextureRegion mHeartTextureRegion;
    private Sprite mHeartSprite;
    private ChangeableText mHeartChangeableText;
    //pause
    private BitmapTextureAtlas PauseBitmapTextureAtlas;
    private TextureRegion PauseTextureRegion;
    private Sprite PauseSprite;
    //contiues
    private BitmapTextureAtlas TiepTucBitmapTextureAtlas;
    private TextureRegion TiepTucTextureRegion;
    private Sprite TiepTucSprite;
    //sound
    private BitmapTextureAtlas SoundBitmapTextureAtlas;
    private TextureRegion SoundOnTextureRegion;
    private TextureRegion SoundOffTextureRegion;
    private Sprite SoundOnSprite;
    private Sprite SoundOffSprite;
    // anh loading
    private BitmapTextureAtlas NinjaLoadingBitmapTextureAtlas;
    private TextureRegion ninjaLoadingTextureRegion;
    private Sprite	ninjaLoadingSprite;
    // Font
    private BitmapTextureAtlas mFontBitmapAtlast;
    private TextureRegion mFontTextureRegion;
    private Font mFont;
    //text diem va lever
    private int DIEM = 0;
    private int diem1 = 0;
    private ChangeableText TextDiem;
    private ChangeableText TextLevel;
    //prite A,B
    private BitmapTextureAtlas ABBitmapTextureAtlas;
    private TextureRegion ATextureRegion;
    private TextureRegion BTextureRegion;
    private Sprite A, B;
    //sound effect
    private Sound sound_outch;
    private Sound sound_resetplayer,sound_chem,sound_danhnhau;
    // position menu
    protected static final int CONTINUE = 0;
    protected static final int NEWGAME = CONTINUE + 1;
    protected static final int MAINMENU = NEWGAME + 1;
    protected static final int MENU_QUIT = MAINMENU + 1;
    
    protected MenuScene mMenuScene;
    
    private Database db = new Database(this);
    //finish game
    private int MAX_SO_QUAI_VAT = 5;
    private int DEM_SO_QUAI_BI_TIEU_DIET = 0;   
    
    private boolean OVERGAME = false;
    private boolean WIN = false;
    private boolean NEXT_LEVEL = false;
    
    private String mTen_Map = "";
    
    // init
    private int LEVEL = 1;
    
    private int HEART = 3;
    // bien de luu trang thai action
    public Boolean mIsNhan = false;
    public Boolean mIsFight = false;
    
	public Engine onLoadEngine() {
		// TODO Auto-generated method stub
		Bundle b = getIntent().getExtras();
		if(b != null){
			LEVEL = b.getInt("LEVEL");
			MAX_SO_QUAI_VAT = b.getInt("MAX_SO_QUAI_VAT");
			mTen_Map = b.getString("TEN_MAPS");
			DIEM = b.getInt("DIEM");
			HEART = b.getInt("HEART");
		}
		else{
			LEVEL = 1;
			MAX_SO_QUAI_VAT = 5;
			mTen_Map="testsize.tmx";
			
		
		}
		DEM_SO_QUAI_BI_TIEU_DIET = 0;
		mQuaivat = new quaivat(MAX_SO_QUAI_VAT);
		mPlayer = new Player();
		mPlayer.setHeart(HEART);
		
		mCamera = new BoundCamera(0, 0, Static_Const.CAMERA_WIDTH, Static_Const.CAMERA_HEIGHT);
		Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
				new RatioResolutionPolicy(Static_Const.CAMERA_WIDTH, Static_Const.CAMERA_HEIGHT),
				this.mCamera).setNeedsSound(true).setNeedsMusic(true));
		try {
            if(MultiTouch.isSupported(this)) {
                    engine.setTouchController(new MultiTouchController());
                    if(MultiTouch.isSupportedDistinct(this)) {                      
                    }else {}
            } else {}
	     } catch (Exception e) {}
		
		return engine;
	}
	
	public void onLoadResources() {
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("image/");
		NinjaLoadingBitmapTextureAtlas = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		ninjaLoadingTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(NinjaLoadingBitmapTextureAtlas, this, "Loading.png", 0, 0);
		mEngine.getTextureManager().loadTexture(NinjaLoadingBitmapTextureAtlas);
	}

	public Scene onLoadScene() {
		mScene_loading = new Scene();
		//mScene_loading.setBackgroundEnabled(false);
		ninjaLoadingSprite = new Sprite(0, 0, ninjaLoadingTextureRegion);
		mScene_loading.attachChild(ninjaLoadingSprite);
		
		return mScene_loading;
	}

	public void onLoadComplete() {
		// TODO Auto-generated method stub
		mEngine.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback() {
			
			public void onTimePassed(TimerHandler pTimerHandler) {
				// TODO Auto-generated method stub
				mEngine.unregisterUpdateHandler(pTimerHandler);
				LoadResources();
				LoadScene();
				mEngine.setScene(mScene);
			}
		}));
		
	}
	public void LoadResources() {
		// load player
		mPlayer.onLoadResources(mEngine, this);
		// quai vat
		mQuaivat.onLoadResources(MainGame_BaseGame.this.mEngine, MainGame_BaseGame.this);
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("Control/");
		
		this.PauseBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.PauseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.PauseBitmapTextureAtlas, this, "pause.png", 0, 0);
        this.mEngine.getTextureManager().loadTextures(this.PauseBitmapTextureAtlas);
		
		//control
        mOnControlScreenTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnControlScreenTexture, 
        														this, "ControlBase.png", 0, 0);
        this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnControlScreenTexture, 
        														this, "ControlKnob.png", 128, 0);
        this.mEngine.getTextureManager().loadTextures(mOnControlScreenTexture);
        //icon Fight
        mFightTexture = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mFightTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mFightTexture, this,"Fight.png", 0, 0);
        mEngine.getTextureManager().loadTexture(mFightTexture);
       
        //icon Jump
        mJumpTexture = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mJumpTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mJumpTexture, this, "Jump.png", 0, 0);
        mEngine.getTextureManager().loadTexture(mJumpTexture);
       
        //load sound
        SoundBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        SoundOnTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.SoundBitmapTextureAtlas, this, "sound_on.png", 0, 0);
        SoundOffTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.SoundBitmapTextureAtlas, this, "sound_off.png", 32, 0);
        mEngine.getTextureManager().loadTextures(this.SoundBitmapTextureAtlas);
        // load pause
        PauseBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        PauseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.PauseBitmapTextureAtlas, this, "pause.png", 0, 0);
        mEngine.getTextureManager().loadTextures(this.PauseBitmapTextureAtlas);
        // load heart
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("player/");
        mHeartTexture = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mHeartTextureRegion= BitmapTextureAtlasTextureRegionFactory.createFromAsset(mHeartTexture, this, "heart.png", 0, 0);
        mEngine.getTextureManager().loadTexture(mHeartTexture);
        //Font
        mFontBitmapAtlast = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        mFont = new Font(mFontBitmapAtlast, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 34, true, Color.BLACK);
        mEngine.getTextureManager().loadTexture(mFontBitmapAtlast);
        mEngine.getFontManager().loadFont(mFont);
      //tiep tuc
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("image/");
        this.TiepTucBitmapTextureAtlas = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.TiepTucTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.TiepTucBitmapTextureAtlas, this, "tieptuc.png", 0, 0);
        this.mEngine.getTextureManager().loadTextures(this.TiepTucBitmapTextureAtlas);
        //A,B
        this.ABBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.ATextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.ABBitmapTextureAtlas, this, "A.png", 0, 0);
        this.BTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.ABBitmapTextureAtlas, this, "B.png", 16, 0);
        this.mEngine.getTextureManager().loadTextures(this.ABBitmapTextureAtlas);
        //sound
        SoundFactory.setAssetBasePath("soundeffect/");
     
        try {
            sound_resetplayer = SoundFactory.createSoundFromAsset(mEngine.getSoundManager(), this, "die.wav");
            sound_outch = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "out.wav");
            sound_chem = SoundFactory.createSoundFromAsset(mEngine.getSoundManager(), this, "chemdao.mp3");
            sound_danhnhau = SoundFactory.createSoundFromAsset(mEngine.getSoundManager(), this, "chemtrung.mp3");
    } catch (final IOException e) {
            Debug.e(e);
    }

        
		
	}
	public void LoadScene()
	{
		this.mEngine.registerUpdateHandler(new FPSLogger());
		mScene = new Scene();
		mScene.registerUpdateHandler(updateHandler);
		
		mScene.setBackground(new ColorBackground(1f, 1f, 1f));
		// load map
		mTMXTiledMap = Map.getTMXTiledMap(mScene, mEngine, this, mTen_Map);
		mMap = new MyMap(mTMXTiledMap.getTileColumns(), mTMXTiledMap.getTileRows());
		ArrayList<TMXLayer> mapLayers = mTMXTiledMap.getTMXLayers();
		for(TMXLayer layer : mapLayers)
		{
			if(layer.getName().equals("vatcan_player"))
			{
				mTMXVatCan_Layer = layer;
				continue;
			}
			else if(layer.getName().equals("vatcan_quaivat"))
			{
				mTMXVatcan_QuaiVat = layer;
				continue;
			}
			mScene.attachChild(layer);
				
		}

	
		mCamera.setBounds(0, mTMXVatCan_Layer.getWidth(), 0, mTMXVatCan_Layer.getHeight());
		mCamera.setBoundsEnabled(true);
	
		mPlayer.setPositionXY(16, 166);
		mPlayer.onLoadScene(mScene);
		mPlayer.setChuyendongMap(mCamera, mMap);
		// quai vat
		mQuaivat.onLoadScene(mScene);
		mQuaivat.setTMXTiledMap(mTMXTiledMap);
		mQuaivat.setTMXLayer(mTMXVatcan_QuaiVat);
		mQuaivat.reset();
		// digitalonscreencontrol
		mDigitalOnScreenControl = new DigitalOnScreenControl(0, Static_Const.CAMERA_HEIGHT - mOnScreenControlBaseTextureRegion.getHeight(),
				mCamera, mOnScreenControlBaseTextureRegion, mOnScreenControlKnobTextureRegion, 0.1f,  new IOnScreenControlListener() {
		float pX = 0 ,pY = 0;	
		public void onControlChange(BaseOnScreenControl pBaseOnScreenControl,
							float pValueX, float pValueY) {
						// TODO Auto-generated method stub
						
						if(pValueX >0 && mPlayer.getStatus_player() != Status_player.MOVE_RIGHT)
						{
							mPlayer.setStatus_player(Status_player.MOVE_RIGHT);
							mStatus_DigitalOnScreenControl = Status_player.MOVE_RIGHT;
							pX= mPlayer.player1_animatedSprite.getWidth() + mPlayer.getPositionX();
							pY= mPlayer.player1_animatedSprite.getHeight()/2 + mPlayer.getPositionY();
							
							
						}
						else if(pValueX<0 && mPlayer.getStatus_player() != Status_player.MOVE_LEFT)
						{
							mPlayer.setStatus_player(Status_player.MOVE_LEFT);
							mStatus_DigitalOnScreenControl = Status_player.MOVE_LEFT;
							pX = mPlayer.getPositionX();
							pY= mPlayer.player1_animatedSprite.getHeight()/2 + mPlayer.getPositionY();
						}
						else
						{
							switch(mStatus_DigitalOnScreenControl)
							{
								case Status_player.MOVE_RIGHT : {
									mPlayer.setStatus_player(Status_player.UN_MOVE_RIGHT);
									break;
								}
								case Status_player.MOVE_LEFT : {
									mPlayer.setStatus_player(Status_player.UN_MOVE_LEFT);
									break;
								}
								default: break;
															
							}
						}
						if(pValueX !=0 )
						{
							
							TMXTile  tmxtile = mTMXVatCan_Layer.getTMXTileAt(pX + pValueX*3,pY+pValueY*3);
							try
							{
								if(tmxtile == null){}
								else {
									TMXProperties<TMXTileProperty> mTMXProperties= tmxtile.getTMXTileProperties(mTMXTiledMap);
									TMXTileProperty mTMXTileProperty = mTMXProperties.get(0);
									if(mTMXTileProperty.getName().equals("vatcan_player")){
										
									}
									
								}
								
							
						}
							catch(Exception e)
							{
								mPlayer.MoveLienTucXY(pValueX*2, pValueY*2);
								Log.e("pixxxxxxxxxx","gia tri" + mPlayer.player1_animatedSprite.getX() );
								if(((mPlayer.player1_animatedSprite.getX()+mPlayer.player1_animatedSprite.getWidth()-18)>= Static_Const.CAMERA_WIDTH/2
										&& mPlayer.getStatus_player() == Status_player.MOVE_RIGHT)
										&&(((mPlayer.player1_animatedSprite.getX()+mPlayer.player1_animatedSprite.getWidth())<= 2*Static_Const.CAMERA_WIDTH-226)
										&& mPlayer.getStatus_player() == Status_player.MOVE_RIGHT))
								{
									
									mFightSprite.setPosition(4+mFightSprite.getX(), mFightSprite.getY());
									mJumpSprite.setPosition(4+mJumpSprite.getX(), mJumpSprite.getY());
									mHeartSprite.setPosition(4+mHeartSprite.getX(), mHeartSprite.getY());
									mHeartChangeableText.setPosition(4+mHeartChangeableText.getX(), mHeartChangeableText.getY());
									TextDiem.setPosition(4+TextDiem.getX(), TextDiem.getY());
									TextLevel.setPosition(4+TextLevel.getX(), TextLevel.getY());
									SoundOffSprite.setPosition(4+SoundOffSprite.getX(), SoundOffSprite.getY());
									SoundOnSprite.setPosition(4+SoundOnSprite.getX(), SoundOnSprite.getY());
									
									
									
									
								}
								if(((mPlayer.player1_animatedSprite.getX()+mPlayer.player1_animatedSprite.getWidth()-18)>= Static_Const.CAMERA_WIDTH/2
										&& mPlayer.getStatus_player() == Status_player.MOVE_LEFT)
										&&(((mPlayer.player1_animatedSprite.getX()+mPlayer.player1_animatedSprite.getWidth())<= 2*Static_Const.CAMERA_WIDTH-226)
										&& mPlayer.getStatus_player() == Status_player.MOVE_LEFT))
								{
									
									mFightSprite.setPosition(mFightSprite.getX()-4, mFightSprite.getY());
									mJumpSprite.setPosition(mJumpSprite.getX()-4, mJumpSprite.getY());
									mHeartSprite.setPosition(mHeartSprite.getX()-4, mHeartSprite.getY());
									mHeartChangeableText.setPosition(mHeartChangeableText.getX()-4, mHeartChangeableText.getY());
									TextDiem.setPosition(TextDiem.getX()-4, TextDiem.getY());
									TextLevel.setPosition(TextLevel.getX()-4, TextLevel.getY());
									SoundOffSprite.setPosition(SoundOffSprite.getX()-4, SoundOffSprite.getY());
									SoundOnSprite.setPosition(SoundOnSprite.getX()-4, SoundOnSprite.getY());
									
								}
							}
							
						
						
					}
					}
				});
			mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
			mDigitalOnScreenControl.getControlBase().setAlpha(0.7f);
			mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
			mDigitalOnScreenControl.getControlBase().setScale(0.8f);
			mDigitalOnScreenControl.getControlKnob().setScale(0.8f);
			mDigitalOnScreenControl.refreshControlKnobPosition();
			mScene.setChildScene(mDigitalOnScreenControl);
		
		
		// icon Fight
		mFightSprite = new Sprite(Static_Const.CAMERA_WIDTH-mFightTextureRegion.getWidth()-10, 
						Static_Const.CAMERA_HEIGHT-mFightTextureRegion.getHeight(), mFightTextureRegion){
			@Override
			public boolean onAreaTouched(
					TouchEvent pSceneTouchEvent,float pTouchAreaLocalX,float pTouchAreaLocalY) {
				// TODO Auto-generated method stub
				if(Static_Const.AmThanh)
				{
					sound_chem.play();
				}
				if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN )
				{
					mIsNhan = true;
					mIsFight = true;
				}
				else 
				{
					mIsFight = false;
				}
				if(mIsNhan == true && mPlayer.getStatus_player()==Status_player.UN_MOVE_RIGHT)
				{
				mPlayer.setStatus_player(Status_player.CHEM_PHAI);
				Thread th = new Thread(new Runnable() {
					
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mIsNhan = false;
					}
				});
				}
					if(mIsNhan == true&& mPlayer.getStatus_player()==Status_player.UN_MOVE_LEFT)
					{
						mPlayer.setStatus_player(Status_player.CHEM_TRAI);
						Thread th = new Thread(new Runnable() {
							public void run() {
								// TODO Auto-generated method stub
								try {
									Thread.sleep(500);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								mIsNhan = false;
							}
						});
					}
					
					
					
				
				
				return true;
			}
		};
		mFightSprite.setAlpha(0.5f);
		mScene.attachChild(mFightSprite);
		mScene.registerTouchArea(mFightSprite);
		//icon Jump
		mJumpSprite = new Sprite(Static_Const.CAMERA_WIDTH- mFightTextureRegion.getWidth()-mJumpTextureRegion.getWidth()-20,
				Static_Const.CAMERA_HEIGHT-mFightTextureRegion.getHeight(), mJumpTextureRegion);
		mJumpSprite.setAlpha(0.5f);
		mScene.attachChild(mJumpSprite);
		//sound on
		SoundOnSprite = new Sprite(Static_Const.CAMERA_WIDTH - 64, 1, this.SoundOnTextureRegion){
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        			if(Static_Const.AmThanh)
        				sound_outch.play(); 
        			Static_Const.AmThanh = !Static_Const.AmThanh;
        			SoundOffSprite.setPosition(SoundOnSprite.getX(), SoundOnSprite.getY());
        			SoundOnSprite.setPosition(-100, -100);
        		}
        		return true;
			}
		};     
        SoundOnSprite.setAlpha(0.5f);
        mScene.attachChild(SoundOnSprite);
        mScene.registerTouchArea(SoundOnSprite);
        // sound off
        this.SoundOffSprite = new Sprite(Static_Const.CAMERA_WIDTH - 64, 1, this.SoundOffTextureRegion){
        	@Override
        	public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
        			float pTouchAreaLocalX, float pTouchAreaLocalY) {
        		// TODO Auto-generated method stub
        		if(pSceneTouchEvent.getAction()== TouchEvent.ACTION_DOWN)
        		{
        			if(Static_Const.AmThanh)
        				sound_outch.play(); 
        			Static_Const.AmThanh = !Static_Const.AmThanh;
        			SoundOnSprite.setPosition(SoundOffSprite.getX(), SoundOffSprite.getY());
        			SoundOffSprite.setPosition(-100, -100);
        		}
        		return true;
        	}
        };
        this.SoundOffSprite.setAlpha(0.5f);
        mScene.attachChild(SoundOffSprite);
        mScene.registerTouchArea(SoundOffSprite);
        //set vi tri sound on va sound off
        if(Static_Const.AmThanh){
        	SoundOnSprite.setPosition(Static_Const.CAMERA_WIDTH - 64, 1);
        	SoundOffSprite.setPosition(-100, -100);
        }else{
        	SoundOnSprite.setPosition(-100, -100);
        	SoundOffSprite.setPosition(Static_Const.CAMERA_WIDTH - 64, 1);
        }
        //pause
        PauseSprite = new Sprite(Static_Const.CAMERA_WIDTH - 32, 1, this.PauseTextureRegion)
        {
        	@Override
        	public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
        			float pTouchAreaLocalX, float pTouchAreaLocalY) {
        		
        		if(pSceneTouchEvent.getAction()== TouchEvent.ACTION_DOWN)
        		{
        			if(Static_Const.AmThanh)
        				sound_outch.play();
        			MainGame_BaseGame.this.mScene.setChildScene(MainGame_BaseGame.this.mMenuScene, false, true, true);
        		}
        		return false;
        	}
        };
        this.PauseSprite.setAlpha(1f);
        mScene.attachChild(PauseSprite);
        mScene.registerTouchArea(PauseSprite);
        // hien thi heart (so lan choi cua nhan vat)
        mHeartSprite = new Sprite(Static_Const.CAMERA_WIDTH/2 - mHeartTextureRegion.getWidth()/2, 0, mHeartTextureRegion);
        mScene.attachChild(mHeartSprite);
        mHeartChangeableText = new ChangeableText(mHeartSprite.getX() - 20, -10, mFont,String.valueOf(mPlayer.getHeart()),2);
        mScene.attachChild(mHeartChangeableText);
        TextDiem = new ChangeableText(0,-10,this.mFont,String.valueOf(DIEM),10);
        mScene.attachChild(TextDiem);
        
        TextLevel = new ChangeableText(Static_Const.CAMERA_WIDTH/2 - 50,Static_Const.CAMERA_HEIGHT-42,this.mFont,"Level "+String.valueOf(LEVEL),10);//Hiá»‡n thá»‹ tá»‘i Ä‘a 10 kA½ tá»±
        mScene.attachChild(TextLevel);
        //
        TiepTucSprite = new Sprite(Static_Const.CAMERA_WIDTH - this.TiepTucTextureRegion.getWidth()/2,
				Static_Const.CAMERA_HEIGHT - this.TiepTucTextureRegion.getHeight()/2, this.TiepTucTextureRegion){
        	@Override
            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        		if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN && TiepTucSprite.isVisible()){
					if(Static_Const.AmThanh)
					{
						sound_outch.play();
					}
        			if(LEVEL == Static_Const.TONG_SO_LEVEL){
						Intent i = new Intent(MainGame_BaseGame.this, ChienThang.class);
						i.putExtra("diem", DIEM);
						startActivity(i);
						finish();		
					}else
						nextLevel();
        		}
        		return true;
            }
        };
        TiepTucSprite.setVisible(false);
        mScene.attachChild(TiepTucSprite);
        mScene.registerTouchArea(TiepTucSprite);
        //a,b
        this.A = new Sprite(-100, -100 , this.ATextureRegion);
        A.setVisible(false);
        mScene.attachChild(A);
        mScene.registerTouchArea(A);
        
        this.B = new Sprite(-100, -100 , this.BTextureRegion);
        B.setVisible(false);
        mScene.attachChild(B);
        mScene.registerTouchArea(B);
        // khoi tao menu
        this.mMenuScene = this.createMenuScene();
        
		
		
	}

	IUpdateHandler updateHandler = new IUpdateHandler() {
			
			public void reset() {
				// TODO Auto-generated method stub
				
			}
			
			public void onUpdate(float pSecondsElapsed) {
				if(!OVERGAME)
				{
					if(!WIN)
					{
						try{
							for(int i=0 ; i<MAX_SO_QUAI_VAT;i++)
							{
								if(mQuaivat.quaivat_1[i].mSta_AnimatedSprite.isVisible())
								{
									mQuaivat.quaivat_1[i].moveRandom();
								}
								if(vaCham(mQuaivat.quaivat_1[i].mSta_AnimatedSprite, mPlayer.player1_animatedSprite)&&
										mQuaivat.quaivat_1[i].mSta_AnimatedSprite.isVisible())
								{
									
									if(mIsFight== false)
									{
										if(Static_Const.AmThanh)
										{
											sound_resetplayer.play();
										}
										mPlayer.MoveXY(16, 166);
										mPlayer.setHeart(mPlayer.getHeart()-1);
										mHeartChangeableText.setText(String.valueOf(mPlayer.getHeart()));
									if(mPlayer.getHeart()<=0)
									{
										OVERGAME = true;
										System.out.println("da thua");
									}
									mFightSprite.setPosition(Static_Const.CAMERA_WIDTH-mFightTextureRegion.getWidth()-10, 
											Static_Const.CAMERA_HEIGHT-mFightTextureRegion.getHeight());
									mJumpSprite.setPosition(Static_Const.CAMERA_WIDTH- mFightTextureRegion.getWidth()-mJumpTextureRegion.getWidth()-20,
											Static_Const.CAMERA_HEIGHT-mFightTextureRegion.getHeight());
									SoundOnSprite.setPosition(Static_Const.CAMERA_WIDTH - 64, 1);
									SoundOffSprite.setPosition(Static_Const.CAMERA_WIDTH - 64, 1);
									mHeartSprite.setPosition(Static_Const.CAMERA_WIDTH/2 - mHeartTextureRegion.getWidth()/2, 0);
									mHeartChangeableText.setPosition(mHeartSprite.getX() - 20, -10);
									TextDiem.setPosition(0,-10);
									TextLevel.setPosition(Static_Const.CAMERA_WIDTH/2 - 50,Static_Const.CAMERA_HEIGHT-42);
									
									}
									if(mIsFight == true)
									{
										if(Static_Const.AmThanh)
										{
											sound_danhnhau.play();
										}
										DIEM = DIEM + 50;
										diem1 = diem1 + 50;
										DEM_SO_QUAI_BI_TIEU_DIET ++;
										if(DEM_SO_QUAI_BI_TIEU_DIET == MAX_SO_QUAI_VAT)
										{
											WIN = true;
											System.out.println("da thang");
										}
										mQuaivat.quaivat_1[i].mSta_AnimatedSprite.setVisible(false);
										mQuaivat.quaivat_1[i].mSta_AnimatedSprite.setPosition(-100,-100);
										TextDiem.setText(String.valueOf(DIEM), true);
									}
								}
							}
						}
						catch(Exception e){
							System.out.println("loi ne: "+e.toString());
						}
					}
					//win
					else
					{
						if(NEXT_LEVEL == false)
						{
							TiepTucSprite.setVisible(true);
							
							TiepTucSprite.setPosition(2*Static_Const.CAMERA_WIDTH - TiepTucSprite.getWidth() -10, Static_Const.CAMERA_HEIGHT/2-20);
						}
					}
						
					
				}
				//game over
				else
				{
					if(db.kt_luu(DIEM))
					{
						Intent i = new Intent(MainGame_BaseGame.this, Luudiem.class);
						i.putExtra("diem", DIEM);
						MainGame_BaseGame.this.startActivity(i);
						MainGame_BaseGame.this.finish();	
					}
					else
					{
					Intent i = new Intent(MainGame_BaseGame.this,GameOver.class);
					MainGame_BaseGame.this.startActivity(i);
					MainGame_BaseGame.this.finish();
					}
					
				}
			
				
			}
		};
		private void nextLevel(){
			Intent intent_MainGame_BaseGame = new Intent(MainGame_BaseGame.this, MainGame_BaseGame.class);
			
			if(LEVEL+1 < Static_Const.TONG_SO_LEVEL)
				LEVEL++;
			dinhNghiaCacBienThayDoi();
			HEART = mPlayer.getHeart();
			intent_MainGame_BaseGame.putExtra("DIEM", DIEM);
			intent_MainGame_BaseGame.putExtra("HEART", HEART + 3);
			
			intent_MainGame_BaseGame.putExtra("LEVEL", LEVEL);
			intent_MainGame_BaseGame.putExtra("MAX_SO_QUAI_VAT", MAX_SO_QUAI_VAT);
			intent_MainGame_BaseGame.putExtra("TEN_MAPS", mTen_Map + ".tmx");
			
	    	MainGame_BaseGame.this.startActivity(intent_MainGame_BaseGame);
	    	MainGame_BaseGame.this.finish();
		}
		public void dinhNghiaCacBienThayDoi(){
			
			switch(LEVEL){
			case 1:
				MAX_SO_QUAI_VAT = 5;
				mTen_Map = "testsize";
				break;
			case 2:
				MAX_SO_QUAI_VAT = 8;
				mTen_Map = "level1" ;
				break;
			
			}
		}
		public boolean vaCham(AnimatedSprite a, AnimatedSprite b){		
			//A.setPosition(a.getX() + 20,a.getY());
			//B.setPosition(b.getX() +2,b.getY());
			if(a.collidesWith(b))
				return true;
			return false;
		}
		protected MenuScene createMenuScene() {
	        final MenuScene menuScene = new MenuScene(MainGame_BaseGame.this.mCamera);
	       
	        final IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(CONTINUE, MainGame_BaseGame.this.mFont, "TIẾP TỤC"), 1.0f,0.0f,0.0f, 255.0f,255.0f,255.0f);
	        resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
	        menuScene.addMenuItem(resetMenuItem);
	        
	        final IMenuItem NewGameMenuItem = new ColorMenuItemDecorator(new TextMenuItem(NEWGAME, MainGame_BaseGame.this.mFont, "CHƠI LẠI"), 1.0f,0.0f,0.0f, 255.0f,255.0f,255.0f);
	        NewGameMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
	        menuScene.addMenuItem(NewGameMenuItem);
	        
	        final IMenuItem MainMenuMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MAINMENU, MainGame_BaseGame.this.mFont, "MENU CHÍNH"), 1.0f,0.0f,0.0f, 255.0f,255.0f,255.0f);
	        MainMenuMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
	        menuScene.addMenuItem(MainMenuMenuItem);

	        final IMenuItem quitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_QUIT, this.mFont, "THOÁT"), 1.0f,0.0f,0.0f, 255.0f,255.0f,255.0f);
	        quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
	        menuScene.addMenuItem(quitMenuItem);

	        menuScene.buildAnimations();
	        menuScene.setBackgroundEnabled(false);
	        menuScene.setOnMenuItemClickListener(this);
	        return menuScene;
		}

	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		switch(pMenuItem.getID()) {
        case CONTINUE:
            	if(Static_Const.AmThanh)
            		sound_outch.play();
        		MainGame_BaseGame.this.mScene.back();                    	
                this.mMenuScene.reset();
                this.mScene.setChildScene(mDigitalOnScreenControl);
                return true;
        case NEWGAME:
        	if(Static_Const.AmThanh)
        		sound_outch.play();
            	Intent i = new Intent(MainGame_BaseGame.this, MainGame_BaseGame.class);
            	MainGame_BaseGame.this.startActivity(i);
            	MainGame_BaseGame.this.finish();
                return true;
        case MAINMENU:
        	if(Static_Const.AmThanh)
        		sound_outch.play();
            	Intent intent_BomActivity = new Intent(MainGame_BaseGame.this, NinjaActivity.class);
            	MainGame_BaseGame.this.startActivity(intent_BomActivity);
            	MainGame_BaseGame.this.finish();
                return true;
        case MENU_QUIT:
        	if(Static_Const.AmThanh)
        		sound_outch.play();
        	AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainGame_BaseGame.this);
			alertDialog.setTitle("Exit");
			alertDialog.setMessage("Bạn Có Muốn Thoát Ra khỏi Game Không ?");
			alertDialog.setIcon(R.drawable.icon_exit);
			alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				
					finish();
				}
			});
			alertDialog.setNegativeButton("NO",new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			});
			alertDialog.show();
                return true;
        default:
                return false;
			}
	}

	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		return false;
	}

	

}